package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.DeviceMsgData;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by shijunting on 15-5-25.
 */
public class MyDeviceMsg extends CcMsgStructure {

    private static final String TAG = "MyDeviceMsg";

    private Message mmCallback;
    private ArrayList<DeviceMsgData> deviceMsgDatas = new ArrayList<DeviceMsgData>();

    public MyDeviceMsg(Message callback) {
        mmCallback = callback;
    }

    @Override
    public void onReceive(JSONObject data) {
        int isOpen = 0;
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            isOpen = jsonObject.getInt("is_open");
            if(jsonObject.has("devices")){
                JSONArray jsonArray = jsonObject.getJSONArray("devices");
                for (int i = 0; i < jsonArray.length(); i++) {
                    DeviceMsgData deviceMsgData = new DeviceMsgData();
                    JSONObject item = jsonArray.getJSONObject(i);
                    deviceMsgData.setId(item.getString("id"));
                    deviceMsgData.setDeviceName(item.getString("device_name"));
                    deviceMsgData.setDeviceType(item.getString("device_type"));
                    deviceMsgData.setDeviceId(item.getString("device_number"));
                    deviceMsgData.setGroupDefault(item.getString("group_default"));
                    deviceMsgDatas.add(deviceMsgData);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (mmCallback != null) {
            mmCallback.obj = deviceMsgDatas;
            mmCallback.arg2 = isOpen;//1.管理员已打开更换设备，0.未
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }

    }

    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
